package top.yokey.shopai.zcom.base;

import android.Manifest;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.Application;
import android.content.ComponentName;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Vibrator;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.text.ClipboardManager;
import android.util.TypedValue;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.webkit.WebSettings;
import android.webkit.WebView;

import androidx.annotation.RequiresApi;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;
import androidx.core.graphics.drawable.DrawableCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;

import com.google.android.material.tabs.TabLayout;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.listener.OnBannerListener;

import java.io.File;
import java.lang.reflect.Field;
import java.util.List;
import java.util.Locale;

import top.yokey.shopai.R;
import top.yokey.shopai.zcom.App;
import top.yokey.shopai.zcom.adapter.ViewPagerAdapter;
import top.yokey.shopai.zcom.other.UBLImageLoader;
import top.yokey.shopai.zcom.util.ConvertUtil;
import top.yokey.shopai.zsdk.ShopAISdk;

@SuppressWarnings("ALL")
public abstract class BaseApplication extends Application {

    public int getWidth() {

        return getResources().getDisplayMetrics().widthPixels;

    }

    public int getHeight() {

        return getResources().getDisplayMetrics().heightPixels;

    }

    public int dp2Sp(int dp) {

        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, dp, getResources().getDisplayMetrics());

    }

    public int dp2Px(int dp) {

        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, getResources().getDisplayMetrics());

    }

    public int getColors(int id) {

        return getResources().getColor(id);

    }

    public int getStatusBarHeight() {

        try {
            int x = 0;
            Class<?> cls = null;
            Object object = null;
            Field field = null;
            cls = Class.forName("com.android.internal.R$dimen");
            object = cls.newInstance();
            field = cls.getField("status_bar_height");
            x = ConvertUtil.string2Int(field.get(object).toString());
            return getResources().getDimensionPixelSize(x);
        } catch (Exception e) {
            return dp2Px(24);
        }

    }

    public int getDeviceId() {

        try {
            String deviceId = null;
            TelephonyManager telephonyManager = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                deviceId = Settings.System.getString(getContentResolver(), Settings.Secure.ANDROID_ID);
            } else {
                if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
                    return 0;
                }
                deviceId = telephonyManager.getDeviceId();
            }
            return Integer.parseInt(deviceId);
        } catch (Exception e) {
            return 0;
        }

    }

    public void setVibrator() {

        Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
        vibrator.vibrate(100);

    }

    public void setFocus(View view) {

        view.setFocusable(true);
        view.setFocusableInTouchMode(true);
        view.requestFocus();
        view.requestFocusFromTouch();

    }

    public void showKeyboard(View view) {

        InputMethodManager inputMethodManager = (InputMethodManager) view.getContext().getSystemService(INPUT_METHOD_SERVICE);
        inputMethodManager.showSoftInput(view, InputMethodManager.SHOW_FORCED);

    }

    public void setVibrator(long time) {

        Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
        vibrator.vibrate(time);

    }

    public void setClipboard(String content) {

        ClipboardManager clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
        clipboardManager.setText(content);

    }

    public void loadHtml(WebView webView, String content) {

        content = content.replace("src=\"/system", "src=\"" + ShopAISdk.get().getUrl() + "system");
        webView.loadDataWithBaseURL(null, encodeHtml(content), "text/html", "UTF-8", null);

    }

    @RequiresApi(api = Build.VERSION_CODES.P)
    public boolean isMainProcess() {

        return getProcessName() == null || getProcessName().equalsIgnoreCase(getPackageName());

    }

    public boolean isRunForeground() {

        ActivityManager activityManager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> taskList = activityManager.getRunningTasks(1);
        if (taskList != null && !taskList.isEmpty()) {
            ComponentName componentName = taskList.get(0).topActivity;
            return componentName != null && componentName.getPackageName().equals(getPackageName());
        }
        return false;

    }

    public boolean inActivityStack(Class<?> cls) {

        Intent intent = new Intent(this, cls);
        ComponentName componentName = intent.resolveActivity(getPackageManager());
        boolean flag = false;
        if (componentName != null) {
            ActivityManager activityManager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
            List<ActivityManager.RunningTaskInfo> taskInfoList = activityManager.getRunningTasks(32);
            for (ActivityManager.RunningTaskInfo taskInfo : taskInfoList) {
                if (taskInfo.baseActivity.equals(componentName)) {
                    flag = true;
                    break;
                }
            }
        }
        return flag;

    }

    public String getIMSI() {

        try {
            TelephonyManager telephonyManager = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
            return telephonyManager.getSubscriberId();
        } catch (Exception e) {
            return "";
        }

    }

    public String getBrand() {

        return Build.BRAND;

    }

    public String getModel() {

        return Build.MODEL;

    }

    public String getSystem() {

        return "Android " + Build.VERSION.RELEASE;

    }

    public String getVersion() {

        try {
            PackageManager packageManager = getPackageManager();
            PackageInfo packageInfo = packageManager.getPackageInfo(getPackageName(), 0);
            return packageInfo.versionName;
        } catch (Exception e) {
            return "0.0";
        }

    }

    public String getLanguage() {

        return Locale.getDefault().getLanguage();

    }

    public String getAndroidId() {

        try {
            return Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID);
        } catch (Exception e) {
            return "";
        }

    }

    public String getMacAddress() {

        try {
            WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
            WifiInfo wifiInfo = wifiManager.getConnectionInfo();
            return wifiInfo.getMacAddress();
        } catch (Exception e) {
            return "";
        }

    }

    public String encodeHtml(String string) {

        return "<html><head><style type='text/css'>body{padding:0;line-height:28px;}p,span,section,img,table,embed,input,dl,dd,tr,td,video{width:100%;padding:0;margin:0px;color:#333333;line-height:28px;}</style></head><body>" + string + "</body></html>";

    }

    public String handlerHtml(String html, String color) {

        html = html.replace("|HS", "<font color='" + color + "'>");
        html = html.replace("|HE", "</font>");
        return html;

    }

    public Locale[] getLanguages() {

        return Locale.getAvailableLocales();

    }

    public Drawable getDrawables(int drawable) {

        return ContextCompat.getDrawable(this, drawable);

    }

    public Drawable getDrawable(int drawable, int color) {

        Drawable wrappedDrawable = DrawableCompat.wrap(getDrawables(drawable));
        DrawableCompat.setTint(wrappedDrawable, color);
        return wrappedDrawable;

    }

    public Drawable getDrawable(Drawable drawable, int color) {

        Drawable wrappedDrawable = DrawableCompat.wrap(drawable);
        DrawableCompat.setTint(wrappedDrawable, color);
        return wrappedDrawable;

    }

    public GradientDrawable getGradientDrawable(float radius, int color) {

        GradientDrawable gradientDrawable = new GradientDrawable();
        gradientDrawable.setColor(color);
        gradientDrawable.setCornerRadius(radius);
        return gradientDrawable;

    }

    public void startHome(Activity activity) {

        try {
            Intent intent = new Intent();
            intent.setAction("android.intent.action.MAIN");
            intent.addCategory("android.intent.category.HOME");
            activity.startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public void startLocation(Activity activity) {

        try {
            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            activity.startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public void startCall(Activity activity, String mobile) {

        try {
            Intent intent = new Intent(Intent.ACTION_DIAL);
            intent.setData(Uri.parse("tel:" + mobile));
            activity.startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public void startEmail(Activity activity, String email) {

        try {
            Uri uri = Uri.parse("mailto:" + email);
            Intent intent = new Intent(Intent.ACTION_SENDTO, uri);
            activity.startActivity(Intent.createChooser(intent, "请选择邮件类应用"));
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public void startApp(Activity activity, String packName) {

        try {
            Intent intent = getPackageManager().getLaunchIntentForPackage(packName);
            intent.addCategory(Intent.CATEGORY_LAUNCHER);
            intent.setAction(Intent.ACTION_MAIN);
            activity.startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public void startMessage(Activity activity, String mobile) {

        try {
            Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.parse("smsto:" + mobile));
            activity.startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public void startSetting(Activity activity, String packageName) {

        try {
            Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
            intent.setData(Uri.fromParts("package", packageName, null));
            activity.startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public void startInstallApk(Activity activity, String packName, File file) {

        try {
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.setAction(Intent.ACTION_INSTALL_PACKAGE);
            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                Uri contentUri = FileProvider.getUriForFile(this, packName + ".fileProvider", file);
                intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
            } else {
                intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
            }
            activity.startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public void setRecyclerView(RecyclerView recyclerView, RecyclerView.Adapter adapter) {

        recyclerView.setFocusableInTouchMode(false);
        recyclerView.requestFocus();
        recyclerView.setAdapter(adapter);
        recyclerView.setHasFixedSize(true);
        recyclerView.setItemAnimator(null);
        recyclerView.setNestedScrollingEnabled(false);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));

    }

    public void setTabLayout(TabLayout tabLayout, ViewPager viewPager, ViewPagerAdapter adapter) {

        viewPager.setAdapter(adapter);
        tabLayout.setupWithViewPager(viewPager);
        tabLayout.setTabsFromPagerAdapter(adapter);
        tabLayout.setSelectedTabIndicatorColor(App.get().getColors(R.color.accent));
        tabLayout.setTabTextColors(App.get().getColors(R.color.textTwo), App.get().getColors(R.color.accent));
        tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);

    }

    public void setBanner(Banner banner, int radius, List<String> list, OnBannerListener bannerListener) {

        banner.setVisibility(View.VISIBLE);
        banner.setDelayTime(5000);
        banner.setImageLoader(new UBLImageLoader(radius));
        banner.setIndicatorGravity(BannerConfig.CENTER);
        banner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR);
        banner.setOnBannerListener(bannerListener);
        banner.update(list);
        banner.start();

    }

    public void setWebView(WebView webView) {

        WebSettings webSettings = webView.getSettings();
        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        webSettings.setPluginState(WebSettings.PluginState.ON);
        webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);
        webSettings.setLoadsImagesAutomatically(true);
        webSettings.setLoadWithOverviewMode(true);
        webSettings.setDomStorageEnabled(true);
        webSettings.setJavaScriptEnabled(true);
        webSettings.setDatabaseEnabled(true);
        webSettings.setAllowFileAccess(true);
        webSettings.setSupportZoom(false);

    }

}
